package com.example.demo.socket.duplex;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 双向通讯-服务器
 *
 * @author: htc
 * @date: Created in 11:31 2018/11/29.
 */
public class ServerDemo {
    public static void server(Integer port) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        Socket socket = serverSocket.accept();

        // 建立好连接后，从socket中获取输入流，并建立缓冲区进行读取
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder s = new StringBuilder();
        while ((len = inputStream.read()) != 0) {
            s.append(new String(bytes, 0, len, "UTF-8"));
        }
        System.out.println("send from client: " + s);


        //回执给客户端信息
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("this is server !!!".getBytes("UTF-8"));


        //关闭所有连接
        inputStream.close();
        outputStream.close();
        socket.close();
        serverSocket.close();
    }

    public static void main(String[] args) throws IOException {
        server(1111);
    }
}
